﻿using Core.Configuration.Api;
using IconYuan.Manager.Carts;
using IconYuan.Model.DTO.Cart;
using IconYuan.Model.Entity.Carts;
using Microsoft.AspNetCore.Mvc;

namespace IconYuan.Api.Controllers.Carts
{
    /// <summary>
    /// 购物车操作
    /// </summary>
    public class CartController : ApiBase
    {
        readonly CartManager cartSvc;
        public CartController()
        {
            cartSvc = new CartManager();
        }

        /// <summary>
        /// 删除购物车商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public object Clear(DeleteDto model)
        {
            cartSvc.Delete(x => model.cartIds.Contains(x.id));
            return new { cartTotal = 0 };   //购物车商品数
        }

        /// <summary>
        /// 增加购物车
        /// </summary>
        /// <param name="model"></param>
        /// <returns>购物车商品数</returns>
        [HttpPost]
        public async Task<object> Add(AddCartDto model)
        {
            return await AddUpdate(model, 1);
        }

        /// <summary>
        /// 修改购物车数量
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> Update(AddCartDto model)
        {
            return await AddUpdate(model,2);
        }

        private async Task<object> AddUpdate(AddCartDto model,int actionType)
        {
            if (model.userId <= 0) throw new Exception("缺少会员id参数");
            if (model.goodsId <= 0) throw new Exception("请选择商品");

            var old = await cartSvc.GetAsync(x =>
                x.goods_id == model.goodsId &&
                x.goods_sku_id == model.goodsSkuId &&
                x.user_id == model.userId);

            if (old == null)
            {
                old = new Cart();
                old.user_id = model.userId;
                old.goods_id = model.goodsId;
                old.goods_sku_id = model.goodsSkuId;
                old.create_time = DateTime.Now;
            }

            old.update_time = DateTime.Now;
            if (actionType == 1)
            {
                old.goods_num += model.goodsNum;   //增加购物车
            }
            if (actionType == 2)
            {
                old.goods_num = model.goodsNum; //修改购物车数量
            }

            if (old.id > 0)
                await cartSvc.UpdateAsync(old); //修改
            else
                await cartSvc.InsertAsync(old); //新增

            return new { cartTotal = old.goods_num };
        }
    }
}
